﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.IO;
using System.ServiceModel;
using SPRemoteService.Impl;
using System.Text.RegularExpressions;
using SPRemoteService.UI;
using SPRemoteService.WinApp.Properties;
using System.Net.Sockets;
using System.Threading;
using System.Diagnostics;

namespace SPRemoteService.WinApp
{
    public partial class MainForm : Form
    {
        private SharePointConnector _connector;
        private RemoteServiceConfigForm _remoteServiceConfigFrm;
        private char _separatorChar = '*';

        public Thread listenerThread;
        public TcpClient tcpClient;
        public OfficeUtilities.PowerPointUtilities ppUtil;
        public ServiceHost _host;
        public static MainForm CurrentInstance;

        private void WaitForCommand()
        {
            while (true)
            {
                try
                {
                    //Get reader stream
                    StreamReader reader = new StreamReader(tcpClient.GetStream());
                    string line = reader.ReadLine();
                    string command = line.Split(_separatorChar)[0].ToUpper();
                    switch (command)
                    {
                        case "OPENFILE":
                            string siteUrl = line.Split(_separatorChar)[1];
                            string fileUrl = line.Split(_separatorChar)[2];

                            //Download file
                            byte[] byteArr = this.Connector.GetDocument(this.Connector.SiteUrl, this.Connector.SiteUrl.ToString() + fileUrl);
                            System.IO.Directory.CreateDirectory(@".\Temp");
                            string localFileName = @".\Temp\" + Path.GetFileName(fileUrl);
                            File.WriteAllBytes(localFileName, byteArr);

                            //Show desktop
                            Shell32.ShellClass shell = new Shell32.ShellClass();
                            shell.MinimizeAll();

                            if (Path.GetExtension(fileUrl) == ".ppt" || Path.GetExtension(fileUrl) == ".pptx")
                            {
                                //Open file
                                ppUtil = new OfficeUtilities.PowerPointUtilities();
                                ppUtil.StartPowerPoint();
                                ppUtil.OpenFile(Path.GetFullPath(localFileName));
                            }
                            else
                            {
                                //ProcessStartInfo psi = new ProcessStartInfo(Path.GetFullPath(localFileName));
                                //psi.WindowStyle = ProcessWindowStyle.Maximized;
                                //Process.Start(psi);

                                Process process = new Process();
                                // Configure the process using the StartInfo properties.
                                process.StartInfo.FileName = Path.GetFullPath(localFileName);
                                //process.StartInfo.Arguments = "-n";
                                process.StartInfo.WindowStyle = ProcessWindowStyle.Maximized;
                                process.Start();

                                //Process fileProcess = System.Diagnostics.Process.Start(Path.GetFullPath(localFileName));
                            }

                            break;
                        case "PAGEUP":
                            ppUtil.PageUp();
                            break;
                        case "PAGEDOWN":
                            ppUtil.PageDown();
                            break;
                        case "CLOSEFILE":
                            ppUtil.Quit();
                            break;
                        default:
                            break;
                    }

                }
                catch (Exception)
                {
                }
            }
        }

        public MainForm(ServiceHost host)
        {
            InitializeComponent();
            CurrentInstance = this;
            this.listenerThread = new Thread(new ThreadStart(WaitForCommand));
        }

        public SharePointConnector Connector
        {
            get
            {
                return _connector;
            }
            set
            {
                _connector = value;
                LoadTreeView();
            }
        }

        private void LoadTreeView()
        {
            SPTreeView.ItemLimit = 1000;
            SPTreeView.TreeConnector = this.Connector;
            SPTreeView.ContainerTypes = SharePointContainer.TypeEnum.Site |
                               SharePointContainer.TypeEnum.Library |
                               SharePointContainer.TypeEnum.Folder;
            SPTreeView.LibraryBaseTypes = SharePointLibrary.LibraryBaseType.DocumentLibrary;
            SPTreeView.ShowHidden = false;
        }

        private void exitToolStripButton_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            ShowConnectForm();
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            treeViewImageList.Images.Add(Resources._0RootSiteColor);
            treeViewImageList.Images.Add(Resources._1RootSiteGray);
            treeViewImageList.Images.Add(Resources._2SubSiteColor);
            treeViewImageList.Images.Add(Resources._3SubSiteGray);
            treeViewImageList.Images.Add(Resources._4LibraryColor);
            treeViewImageList.Images.Add(Resources._5LibraryGray);
            treeViewImageList.Images.Add(Resources._6FolderColor);
            treeViewImageList.Images.Add(Resources._7FolderGray);

            //treeViewImageList.Images.Add(ShellUtilities.GetFileIcon(System.Environment.SystemDirectory, true, true));
            //treeViewImageList.Images.Add(ShellUtilities.GetFileIcon(System.Environment.SystemDirectory, true, true));

            olvDetails.ShowGroups = false;

            olvDetails.FullRowSelect = true;
            olvDetails.UseHotItem = false;
            olvDetails.UseExplorerTheme = true;

            // Draw the system icon next to the name
            SysImageListHelper helper = new SysImageListHelper(this.olvDetails);
            this.olvColumnFileName.ImageGetter = delegate(object x)
            {
                if (x is ListViewObject)
                {
                    if (((ListViewObject)x).Type == ListViewObject.ObjectType.File)
                    {
                        return helper.GetImageIndex(((ListViewObject)x).Name);
                    }
                    else
                    {
                        return helper.GetImageIndex(System.Environment.SystemDirectory);
                    }
                }
                return helper.GetImageIndex(((FileSystemInfo)x).FullName);
            };

        }

        private void MainForm_Shown(object sender, EventArgs e)
        {
            ShowConnectForm();
        }

        private void ShowConnectForm()
        {
            ConnectForm connFrm = new ConnectForm(this);
            if (connFrm.ShowDialog(this) == System.Windows.Forms.DialogResult.OK)
            {
                SPTreeView.ImageList = treeViewImageList;
                btnRemoteService.Enabled = true;
                remoteServiceToolStripMenuItem.Enabled = true;
            }    
        }

        private void remoteServiceToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (_remoteServiceConfigFrm == null)
            {
                _remoteServiceConfigFrm = new RemoteServiceConfigForm(_host, this);
            }
            _remoteServiceConfigFrm.ShowDialog(this);
        }

        private void connectToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ShowConnectForm();
        }

        private void toolStripButton2_Click(object sender, EventArgs e)
        {
            //SelectTreeNode(new Uri("http://moss2010-hn"), "Dat Library", "{DCF77B56-5C7D-4ED8-B1E6-D4980652AABE}", "");
            if (_remoteServiceConfigFrm == null)
            {
                _remoteServiceConfigFrm = new RemoteServiceConfigForm(_host, this);
            }
            _remoteServiceConfigFrm.ShowDialog(this);
        }

        public bool SelectTreeNode(Uri siteUrl, string libraryDisplayName, string libraryid, string folderNames)
        {
            SharePointLocation spl = new SharePointLocation();
            spl.TargetUrl = siteUrl;
            spl.LibraryDisplayName = libraryDisplayName;
            spl.LibraryId = libraryid;
            spl.FolderNames = folderNames;
            spl.FolderSeparator = '\\';
            SPTreeView.Selected = spl;
            return true;
        }

        private void SPTreeView_AfterSelect(object sender, TreeViewEventArgs e)
        {
            if (e.Node is SharePointTreeNode)
            {
                btnDownload.Enabled = false;
                SharePointTreeNode node = (SharePointTreeNode)e.Node;
                if (node.Container.ContainerType == SharePointContainer.TypeEnum.Library ||
                    node.Container.ContainerType == SharePointContainer.TypeEnum.Folder)
                {
                    List<ListViewObject> objectList = new List<ListViewObject>();

                    //Get folders
                    List<SharePointContainer> folderList =
                        this.Connector.GetFolderList(node.SiteUrl, node.Library.Name, node.ContainerFolderPath, "1000");

                    foreach (var folder in folderList)
                    {
                        objectList.Add(new ListViewObject(node.SiteUrl, folder.Name, folder.Id, folder.Path.ToString(), ListViewObject.ObjectType.Folder));
                    }

                    //Get files
                    List<SharePointField> selectFields = new List<SharePointField>();
                    SharePointField leafField = new SharePointField("FileLeafRef", null, SharePointField.TypeEnum.File, null);
                    SharePointField idField = new SharePointField("ID", null, SharePointField.TypeEnum.DateTime, null);

                    selectFields.Add(leafField);
                    selectFields.Add(idField);

                    List<SharePointContainer> docList =
                        this.Connector.GetDocumentList(node.SiteUrl, node.Library.Name, node.ContainerFolderPath, "1000");

                    foreach (var doc in docList)
                    {
                        objectList.Add(new ListViewObject(node.SiteUrl, doc.Name, doc.Id, doc.Path.ToString(), ListViewObject.ObjectType.File));
                    }

                    this.olvDetails.SetObjects(objectList);
                }
            }
        }

        private void btnDownload_Click(object sender, EventArgs e)
        {
            ListViewObject selectedObj = (ListViewObject)olvDetails.GetSelectedObject();
            SaveFileDialog sfd = new SaveFileDialog();
            sfd.FileName = Path.GetFileName(Regex.Replace(selectedObj.Path, "^[/ ]+|[/ ]+$", String.Empty));
            string extension = Path.GetExtension(Regex.Replace(selectedObj.Path, "^[/ ]+|[/ ]+$", String.Empty));
            if (sfd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                string filePath = sfd.FileName;
                if (Path.GetExtension(filePath) == String.Empty)
                {
                    filePath = filePath + extension;
                }
                String tempPath = selectedObj.Path;
                if (tempPath.EndsWith("/"))
                {
                    tempPath = tempPath.Substring(0, tempPath.Length - 1);
                }
                var byteArr = Connector.GetDocument(selectedObj.SiteUrl, tempPath);
                File.WriteAllBytes(filePath, byteArr);
            }
        }

        private void olvDetails_SelectedIndexChanged(object sender, EventArgs e)
        {
            ListViewObject selectedObj = (ListViewObject)olvDetails.GetSelectedObject();
            if (selectedObj != null && selectedObj.Type == ListViewObject.ObjectType.File)
            {
                btnDownload.Enabled = true;
            }
            else
            {
                btnDownload.Enabled = false;
            }
        }

        private void MainForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            listenerThread.Abort();
        }
    }
}
